<?php

/**
 * group registration.
 *
 * @package    Group
 * @subpackage Model
 */
class Group_Model_Registration
{
	const IDNAME_TAKEN = 'idnameTaken';
	const IDNAME_RESERVED = 'idnameReserved';


	protected $_errorCodes = array();


	/**
	 * Register an account.
	 * returns group id on successful operation, returns NULL otherwise.
	 */
	public function register($accInfo = null)
	{
		$this->_errorCodes = array();

		if (!is_array($accInfo)) {
			throw new Exception('Invalid group information');
		}
		if (empty($accInfo['idname'])) {
			throw new Exception('Group name could not be empty');
		}


		$creator = Account_Model_Session::getAccount();
		if ($creator === NULL) {
			return NULL;
		}


		//TODO: activation method
		$opts = Kernel::getInstance()->getOptions();


		$table = Group_Model_DbTable_Entry::getInstance();
		$idname = $this->_generateSlug($accInfo['idname']);

		// Check for existing idname
		$select = $table->select();
		$select->where('idname= ?', $idname);

		$dbResult = $table->fetchAll($select);

		if ($dbResult->count() > 0) {
			$this->_errorCodes[] = self::IDNAME_TAKEN;
			//TODO: generate instead of returning false
			return NULL;
		}
		//TODO: check for reserved names

		if (count($this->_errorCodes) > 0) {
			return NULL;
		}


        $dbData = array(
			'idname'    => $idname,
			'class'     => 'group',
            'time'      => time() - date('Z'),
            'creator_id'   => $creator->getId(),
			'nicename'  => $accInfo['idname'],
        );

		$insertId = $table->insert($dbData);
		//CHECK: can we use this id?
		if (intval($insertId) === 0) {
			throw new Exception('Query error');
		}

		// Assign the ID
		$groupId = $table->getAdapter()->lastInsertId();


		// Add the creator as member
		Group_Model_Member::groupAddMember($groupId, $creator->getId());

		$member = Group_Model_Member::groupGetMember($groupId, $creator->getId());
		if ($member == NULL) {
			throw new Exception('Something gone wrong!');
		}
		$member->addRole('admin');


		//TODO: email notfication


		return $groupId;
	}

	public function getErrorCodes()
	{
		return $this->_errorCodes;
	}

	//TODO: place this to somewhere else. it's an utility.
	public function _generateSlug($phrase)
	{
		$result = strtolower($phrase);

		$result = preg_replace("/[^a-z0-9\s-]/", "", $result);
		$result = trim(preg_replace("/\s+/", " ", $result));
		$result = trim(substr($result, 0, 45));
		$result = preg_replace("/\s/", "-", $result);

		return $result;
	}
}